package com.FengChaoSystem.filter;


import com.FengChaoSystem.pojo.User;
import com.FengChaoSystem.service.LoginImpl;
import com.FengChaoSystem.service.LoginService.LoginService;
import com.FengChaoSystem.untils.JwtUtil;
import com.Mybatis.scripting.defaults.DefaultParameterHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@WebFilter("/*")
public class LoginFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(LoginFilter.class);
    LoginImpl service=new LoginService();
    /**
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 结合jwt令牌和cookie来做了拦截器，并实现了自动登录的功能
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //判断访问资源路径是否和登录注册相关
        String[] urls = {"/login.html","/imgs/","/js/","/vue/","/element-ui/","/css/","/LoginServlet","/register.html","/registerServlet","/checkCodeServlet","/mail.html","/chooseImage.html","/addImgServlet"};
        // 获取当前访问的资源路径
        String url = req.getRequestURL().toString();

        //循环判断
        for (String u : urls) {
            if(url.contains(u)){
                //找到了
                //放行
                filterChain.doFilter(request, response);
                //break;
                return;
            }
        }


        //1. 判断session中是否有user
        HttpSession session = req.getSession();

        String token = (String) session.getAttribute("token");
        if (token != null) {

            try {
                System.out.println(token);
                JwtUtil.parse(token);
                // token 验证通过，继续执行请求
                filterChain.doFilter(request, response);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else {
            logger.info("已经拦截下了一个请求");
            String username=null;
            String password=null;

            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("username")){
                    username= cookie.getValue();
                } else if (cookie.getName().equals("password")) {
                    password = cookie.getValue();
                }
            }

            if(username!=null&&password!=null){
                User result = service.selectPasswordByUserName(new User(username, null));


                session.setAttribute("phone",result.getPhone());
                session.setAttribute("username",username);
                //获取虚拟路径就可以使其具有多用性
                request.setAttribute("username",username);
                request.setAttribute("identity",result.getIdentity());

                User temp = service.selectIdByUserName(result);
                session.setAttribute("userId",temp.getId());


                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("userId", temp.getId());
                 token = JwtUtil.buildJWT(hashMap);
                session.setAttribute("token",token);
                System.out.println("success");
                filterChain.doFilter(request, response);
                logger.info("自动登录{}",username);
            }
            else{
                // 没有提供 token，返回错误响应
                req.setAttribute("login_msg", "您尚未登陆！");
                req.getRequestDispatcher("/login.html").forward(req, response);}
            }
            else{
            // 没有提供 token，返回错误响应
            req.setAttribute("login_msg", "您尚未登陆！");
            req.getRequestDispatcher("/login.html").forward(req, response);}
        }
    }

    /**
     *
     */
    @Override
    public void destroy() {

    }
}
